package com.hzy.infrastructure.filter;

import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * 系统过滤器
 *
 * @author hzy
 */
public class HttpRequestWrapperFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        String contentType = request.getContentType();
        if (request instanceof HttpServletRequest && Objects.nonNull(contentType) && request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            // 强行 Copy 新的对象 为了能够 多次读取 body 信息
            requestWrapper = new HttpRequestWrapper((HttpServletRequest) request, response);
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }
}